package com.zhentao.service.impl;

import com.alibaba.fastjson.JSON;
import com.zhentao.model.common.article.dto.UserSearchDto;
import com.zhentao.model.common.dtos.ResponseResult;
import com.zhentao.model.common.enums.AppHttpCodeEnum;
import com.zhentao.service.ApArticleSearchService;
import com.zhentao.service.ApArticleService;
import com.zhentao.service.ApUserSearchService;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.naming.directory.SearchResult;
import javax.swing.*;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class ApArticleSearchServiceImpl implements ApArticleSearchService {
   @Autowired
   private RestHighLevelClient restHighLevelClient;
   @Autowired
   private ApUserSearchService apUserSearchService;
    @Override
    public ResponseResult search(UserSearchDto dto) throws IOException {
        //1.检查参数
        if(dto == null || StringUtils.isBlank(dto.getSearchWords())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        apUserSearchService.insert(dto.getSearchWords(),4);
        //2.设置查询条件
        SearchRequest searchRequest = new SearchRequest("app_info_article");
        SearchSourceBuilder builder = new SearchSourceBuilder();

        //布尔查询
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();

        //关键字查询
        QueryStringQueryBuilder queryBuilder = QueryBuilders.queryStringQuery(dto.getSearchWords()).field("title").field("content").defaultOperator(Operator.OR);
        boolQueryBuilder.must(queryBuilder);
        //查询小于mindate的数据
        if(dto.getMinBehotTime() != null){
            RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery("publishTime").lt(dto.getMinBehotTime().getTime());
            boolQueryBuilder.filter(rangeQueryBuilder);
        }

        //分页查询
        builder.from(0);
        builder.size(dto.getPageSize());

        //按照发布时间进行倒叙查询
        builder.sort("publishTime", SortOrder.DESC);

        //设置标题的关键字高显示
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("title");
        highlightBuilder.preTags("<font style='color:red'>");
        highlightBuilder.postTags("</font>");

        builder.highlighter(highlightBuilder);

        builder.query(boolQueryBuilder);
        searchRequest.source(builder);
        SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);

        System.out.println(searchRequest);
        System.out.println(searchResponse);
        //3.结果封装
        List<Map> list = new ArrayList<>();

        SearchHit[] searchHits = searchResponse.getHits().getHits();

        for (SearchHit hit : searchHits) {
            String json = hit.getSourceAsString();
            Map map = JSON.parseObject(json,Map.class);

            //前端用的是h_title,所以需要转换一下
            map.put("h_title", map.get("title"));
            //设置高度
            if(hit.getHighlightFields() != null){
                Text[] texts = hit.getHighlightFields().get("title").getFragments();
                String title = StringUtils.join(texts);
                map.put("h_title", title);
            }
            list.add(map);
        }
        return ResponseResult.okResult(list);
    }
}
